﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Security = JXT.PrimaryKey.Batman.Core.Security;

namespace JXT.PrimaryKey.Batman.Domain.UserSystem.Models
{
    public static class ModelExtensions
    {
        /// <summary>
        /// 合并用户所有权限信息(包括个人和角色)
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns>合并的用户信息</returns>
        public static IEnumerable<Security.Authority> MergeAuthorities(this User user)
        {
            if (user == null)
                throw new ArgumentNullException("user");
            IList<Authority> list = new List<Authority>();
            if (user.Authorities != null)
            {
                foreach (var item in user.Authorities)
                {
                    list.Add(item);
                }
            }
            if (user.Roles != null && user.Roles.Count() > 0)
            {
                foreach (var item in user.Roles)
                {
                    if (item.Authorities == null)
                        continue;
                    foreach (var subItem in item.Authorities)
                    {
                        list.Add(subItem);
                    }
                }
            }
            return list.Select(e => e.ToSecurityAuthority()).ToList();
        }

        public static Security.Authority ToSecurityAuthority(this Authority source)
        {
            return new Security.Authority()
            {
                ExpiresTime = source.ExpiresTime,
                Name = source.Name,
                Priority = (Security.PriorityType)((byte)source.Priority),
                Summary = source.Summary,
                TemplateId = source.TemplateId,
                Type = (Security.AuthorityType)((byte)source.Type),
                Value = source.Value
            };
        }
    }
}
